import 'package:flutter/material.dart';
import 'package:flutter_axrjc/datasource/network/api/KnowledgeApi.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'state.dart';

class KnowledgeForEyeWithTypeLogic extends GetxController
    with GetTickerProviderStateMixin {
  final KnowledgeForEyeWithTypeState state = KnowledgeForEyeWithTypeState();
  var refreshController = RefreshController(initialRefresh: true);
  var page = 1;

  late TabController tabArticle;
  @override
  void onInit() {
    super.onInit();
    tabArticle = TabController(length: state.tabs.length, vsync: this);
    getTabs();
  }

  Future<void> getTabs() async {
    state.tabs.clear();
    try {
      state.tabs.addAll(await KnowledgeApi.getTabs());
      tabArticle = TabController(length: state.tabs.length, vsync: this);
      if (state.tabs.isNotEmpty) {
        state.currentType = "${state.tabs.first.categoryId}";
        getList(isRefresh: true);
      }
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
  }

  Future<void> getList({required bool isRefresh}) async {
    if (isRefresh) {
      page = 1;
      state.list.clear();
    } else {
      page++;
    }
    try {
      state.list.addAll(await KnowledgeApi.getTopThree(
          limit: "10",
          page: '$page',
          categoryId: state.currentType,
          ifText: true));
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
    if (isRefresh) {
      refreshController.refreshCompleted();
    } else {
      refreshController.loadComplete();
    }
  }
}
